package com.liaoyin.travel.service.approval;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.view.moble.approval.ApprovalDetailsView;
import com.liaoyin.travel.view.moble.approval.ApprovalRecordCommunalView;
import com.liaoyin.travel.view.moble.back.approval.ApprovalRecordBackView;
import com.liaoyin.travel.view.user.UserView;
import com.liaoyin.travel.vo.approval.*;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.business.util.AttendanceUtil;
import com.liaoyin.travel.dao.approval.ApprovalRecordMapper;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.approval.*;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.attendance.AttendanceRecordService;
import com.liaoyin.travel.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 审批记录
 *
 * @author kuang.jiazhuo
 * @date 2019-11-22 09:28
 */
@Service
public class ApprovalRecordService extends BaseService<ApprovalRecordMapper, ApprovalRecord> {

    @Resource
    UsersService usersService;

    @Resource
    AskForLeaveRecordService askForLeaveRecordService;

    @Resource
    GoOutRecordService goOutRecordService;

    @Resource
    CardReissueRecordService cardReissueRecordService;

    @Resource
    CardReissuePacketApplicantService cardReissuePacketApplicantService;

    @Resource
    GoOutPacketApplicantService goOutPacketApplicantService;

    @Resource
    AskForLeavePacketApplicantService askForLeavePacketApplicantService;

    @Resource
    AttendanceRecordService attendanceRecordService;

    /**
     * @方法名：checkYourApprover
     * @描述： 传入请求类型查询审批人信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 9:57
     */
    public UserView checkYourApprover(String approvalStatus){
        //获取到用户的登录信息,判断用户是否登录
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        int statistics = 0 ;
        /** 判断有没有加入审批组*/
        //1.补卡
        if(VariableConstants.STRING_CONSTANT_1.equals(approvalStatus)){
            CardReissuePacketApplicant cardReissuePacketApplicant = new CardReissuePacketApplicant().setApplicantId(user.getId());
            statistics = this.cardReissuePacketApplicantService.selectCount(cardReissuePacketApplicant).intValue();
            System.err.println("补卡人数量="+statistics);
        }
        //2.请假
        if(VariableConstants.STRING_CONSTANT_2.equals(approvalStatus)){
            AskForLeavePacketApplicant askForLeavePacketApplicant = new AskForLeavePacketApplicant().setApplicantId(user.getId());
            statistics = this.askForLeavePacketApplicantService.selectCount(askForLeavePacketApplicant).intValue();
            System.err.println("请假人数量="+statistics);
        }
        //3.外出
        if(VariableConstants.STRING_CONSTANT_3.equals(approvalStatus)){
            GoOutPacketApplicant goOutPacketApplicant = new GoOutPacketApplicant().setApplicantId(user.getId());
            statistics = this.goOutPacketApplicantService.selectCount(goOutPacketApplicant).intValue();
            System.err.println("外出人数量="+statistics);
        }
        if(statistics==0){
            throw new BusinessException("did.not.join.the.approval.team");
        }
        //查询到审批人信息

        Users users = this.usersService.selectUsersByApplicant(approvalStatus,user.getId());
        if(users==null){
            throw new BusinessException("not.find.approver");
        }
        //组装成返回的格式
        UserView userView = new UserView();
        String userId = users.getId();
        String nickName = users.getNickName();
        //头像
        String headPicId = users.getHeadPicId();
        FileUpload fileUpload = FileUploadUtil.getFileUpload(headPicId);
        String headPicUrl = null;
        if(fileUpload!=null){
            headPicUrl = fileUpload.getUrl();
        }
        System.err.println("headPicUrl="+headPicUrl);
        userView.setHeadPicUrl(headPicUrl);
        //职务
        String holdOffice = users.getAssumeOfficeDisplay();
        userView.setHoldOffice(holdOffice);
        userView.setUserId(userId);
        userView.setNickName(nickName);
        return userView;
    }

    /**
     * @方法名：insertAskForLeaveRecord
     * @描述： 发起请假审批
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 18:11
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertAskForLeaveRecord(AskForLeaveRequestVo askForLeaveRequestVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

            String approvalRecordId = SnowIdUtil.getInstance().nextId();
            String approvalType = VariableConstants.STRING_CONSTANT_2;
        ApprovalRecordVo approvalRecordVo = askForLeaveRequestVo.getApprovalRecordVo();
        ApprovalRecord approvalRecord = this.insertApprovalRecordByVo(approvalRecordVo);
        //审批的标题
        String approvalTitle = approvalRecordVo.getNickname()+"提交的"+ DictUtil.getDisplay("approvalType",approvalType);
        System.err.println("Nickname="+approvalRecordVo.getNickname());
        approvalRecord.setApprovalTitle(approvalTitle)
                .setApprovalType(approvalType).setId(approvalRecordId)
                //景区id
                .setScenicId(scenicId);
        int result = this.mapper.insert(approvalRecord);
        if(result>0){
            this.askForLeaveRecordService.insertAskForLeaveRecord(askForLeaveRequestVo,approvalRecordId);
        }

        /** 融云消息通知*/
        HashMap<String, String> map = new HashMap<>();
        //消息发起人
        String initiatorId = approvalRecordVo.getInitiatorId();
        map.put("fromUserId",initiatorId);
        //消息接收人
        String approverId = approvalRecordVo.getApproverId();
        map.put("toUserId",approverId);

        //开始请假时间
        String leaveStartTime = askForLeaveRequestVo.getLeaveStartTime();
        //结束请假时间
        String leaveEndTime = askForLeaveRequestVo.getLeaveEndTime();

        JSONObject approvalJsonObject = new JSONObject();
        approvalJsonObject.put("approvalType",approvalType);
        approvalJsonObject.put("approvalTitle",approvalTitle);
        approvalJsonObject.put("leaveStartTime",leaveStartTime);
        approvalJsonObject.put("leaveEndTime",leaveEndTime);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "审批");
        jsonObject.put("extra", approvalJsonObject.toJSONString());
        map.put("objectName","RC:TxtMsg");
        map.put("content",jsonObject.toJSONString());
        map.put("pushContent","审批");

        try {
            String s = RongUtils.groupManagement(map, "7");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @方法名：insertGoOutRecord
     * @描述： 发出外出审批
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 21:14
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertGoOutRecord(GoOutRecordVo goOutRecordVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        String approvalRecordId = SnowIdUtil.getInstance().nextId();
        String approvalType = VariableConstants.STRING_CONSTANT_3;
        ApprovalRecordVo approvalRecordVo = goOutRecordVo.getApprovalRecordVo();
        ApprovalRecord approvalRecord = this.insertApprovalRecordByVo(approvalRecordVo);
        String approvalTitle = approvalRecordVo.getNickname()+"提交的"+ DictUtil.getDisplay("approvalType",approvalType);
        approvalRecord.setApprovalTitle(approvalTitle)
                .setApprovalType(approvalType).setId(approvalRecordId)
                //景区id
                .setScenicId(scenicId);
        int result = this.mapper.insert(approvalRecord);
        if(result>0){
            this.goOutRecordService.insertGoOutRecord(goOutRecordVo,approvalRecordId);
        }
        /** 融云消息通知*/
        HashMap<String, String> map = new HashMap<>();
        //消息发起人
        String initiatorId = approvalRecordVo.getInitiatorId();
        map.put("fromUserId",initiatorId);
        //消息接收人
        String approverId = approvalRecordVo.getApproverId();
        map.put("toUserId",approverId);
        //外出开始时间
        String departureTime = goOutRecordVo.getDepartureTime();
        //外出结束时间
        String endOfOuting = goOutRecordVo.getEndOfOuting();
        //外出时长
        String goOutTime = goOutRecordVo.getGoOutTime();

        JSONObject approvalJsonObject = new JSONObject();
        approvalJsonObject.put("approvalType",approvalType);
        approvalJsonObject.put("approvalTitle",approvalTitle);
        approvalJsonObject.put("departureTime",departureTime);
        approvalJsonObject.put("endOfOuting",endOfOuting);
        approvalJsonObject.put("goOutTime",goOutTime);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "审批");
        jsonObject.put("extra", approvalJsonObject.toJSONString());
        map.put("objectName","RC:TxtMsg");
        map.put("content",jsonObject.toJSONString());
        map.put("pushContent","审批");

        try {
            String s = RongUtils.groupManagement(map, "7");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @方法名：insertCardReissueRecord
     * @描述： 发起补卡审批
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 10:11
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertCardReissueRecord(CardReissueRecordVo cardReissueRecordVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        String approvalRecordId = SnowIdUtil.getInstance().nextId();
        String approvalType = VariableConstants.STRING_CONSTANT_1;
        ApprovalRecordVo approvalRecordVo = cardReissueRecordVo.getApprovalRecordVo();
        ApprovalRecord approvalRecord = this.insertApprovalRecordByVo(approvalRecordVo);
        //审批标题
        String approvalTitle = approvalRecordVo.getNickname()+"提交的"+ DictUtil.getDisplay("approvalType",approvalType);
        approvalRecord.setApprovalTitle(approvalTitle)
                .setApprovalType(approvalType).setId(approvalRecordId)
                //景区id
                .setScenicId(scenicId);
        int result = this.mapper.insert(approvalRecord);
        if(result>0){
            this.cardReissueRecordService.insertCardReissueRecord(cardReissueRecordVo,approvalRecordId);
        }

        /** 融云消息通知*/
        HashMap<String, String> map = new HashMap<>();
        //消息发起人
        String initiatorId = approvalRecordVo.getInitiatorId();
        map.put("fromUserId",initiatorId);
        //消息接收人
        String approverId = approvalRecordVo.getApproverId();
        map.put("toUserId",approverId);
        //补卡班次显示
        String lackOfCardDivisions = cardReissueRecordVo.getLackOfCardDivisions();
        //补卡理由
        String supplementaryCardCause = cardReissueRecordVo.getSupplementaryCardCause();

        JSONObject approvalJsonObject = new JSONObject();
        approvalJsonObject.put("approvalType",approvalType);
        approvalJsonObject.put("approvalTitle",approvalTitle);
        approvalJsonObject.put("lackOfCardDivisions",lackOfCardDivisions);
        approvalJsonObject.put("supplementaryCardCause",supplementaryCardCause);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("content", "审批");
        jsonObject.put("extra", approvalJsonObject.toJSONString());

        map.put("content",jsonObject.toJSONString());
        map.put("pushContent","审批");
        map.put("objectName","RC:TxtMsg");
        try {
            String s = RongUtils.groupManagement(map, "7");
            System.err.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @方法名：insertApprovalRecordByVo
     * @描述： 新增审批记录的公共参数
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 19:26
     */
    @Transactional(rollbackFor = Exception.class)
    public ApprovalRecord insertApprovalRecordByVo(ApprovalRecordVo approvalRecordVo) {
        ApprovalRecord approvalRecord = new ApprovalRecord()
                //审批编号
                .setApprovalNumber(RandomNumberUtil.getApprovalNumber())
                //审批发起人的id
                .setInitiatorId(approvalRecordVo.getInitiatorId())
                //审批人的id
                .setApproverId(approvalRecordVo.getApproverId())
                //审批的发起时间
                .setInitiationTime(LocalDateTime.now())
                //审批的状态:待审核
                .setApprovalStatus(VariableConstants.STRING_CONSTANT_1)
                //审批的创建时间
                .setCreateTime(LocalDateTime.now())
                //默认未删除
                .setIsDelete(VariableConstants.STRING_CONSTANT_0);
        return approvalRecord;
    }

    /**
     * @方法名：selectApprovalRecordByApprover
     * @描述： 管理人员登录后查询自己的审批记录
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 13:09
     * @param num
     * @param size
     */
    public PageInfo<ApprovalRecordCommunalView> selectApprovalRecordByApprover(Integer num, Integer size) {
        //获取到用户的登录信息,判断用户是否登录
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        PageHelper.startPage(num,size);
        List<ApprovalRecord> list = this.mapper.selectApprovalRecordByApproverId(user.getId());
        List<ApprovalRecordCommunalView> approvalRecordCommunalViews = new ArrayList<>();
        if(list!=null){
            list.forEach(approvalRecord -> {
                String approvalType = approvalRecord.getApprovalType();
                ApprovalRecordCommunalView recordAdministratorView = ApprovalRecordCommunalView.builder()
                        .approvalType(approvalType).approvalNumber(approvalRecord.getApprovalNumber())
                        .approvalConsuming(approvalRecord.getApprovalConsuming())
                        .approvalTitle(approvalRecord.getApprovalTitle()).createTime(approvalRecord.getCreateTime())
                        .approvalRecordId(approvalRecord.getId()).approvalStatus(approvalRecord.getApprovalStatus())
                        .build();
                String approvalRecordId = approvalRecord.getId();
                //补卡
                if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                    CardReissueRecord cardReissueRecord = this.cardReissueRecordService.selectCardReissueRecordByApprovalRecordId(approvalRecordId);
                    recordAdministratorView.setSupplementaryCardCause(cardReissueRecord.getSupplementaryCardCause());
                    recordAdministratorView.setClockTimeDisplay(cardReissueRecord.getClockTimeDisplay());
                }
                //请假
                if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                    AskForLeaveRecord askForLeaveRecord = this.askForLeaveRecordService.selectAskForLeaveRecordByApprovalRecordId(approvalRecordId);
                    recordAdministratorView.setLeaveStartTimeAndroid(askForLeaveRecord.getLeaveStartTimeAndroid());
                    recordAdministratorView.setLeaveEndTimeAndroid(askForLeaveRecord.getLeaveEndTimeAndroid());
                }
                //外出
                if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                    GoOutRecord goOutRecord = this.goOutRecordService.selectGoOutRecordByApprovalRecordId(approvalRecordId);
                    recordAdministratorView.setDepartureTime(goOutRecord.getDepartureTime());
                    recordAdministratorView.setEndOfOuting(goOutRecord.getEndOfOuting());
                    recordAdministratorView.setGoOutTime(goOutRecord.getGoOutTime());
                }
                approvalRecordCommunalViews.add(recordAdministratorView);
            });
        }
        PageInfo<ApprovalRecordCommunalView> p = new PageInfo<>(approvalRecordCommunalViews);
        return p;
    }

    /**
     * @方法名：selectRequestRecordByInitiatorId
     * @描述： 员工查看自己的请求记录
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 16:41
     */
    public PageInfo<ApprovalRecordCommunalView> selectRequestRecordByInitiatorId(Integer num, Integer size, String approvalType) {
        //获取到用户的登录信息,判断用户是否登录
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        PageHelper.startPage(num,size);
        List<ApprovalRecord> list = this.mapper.selectRequestRecordByInitiatorId(user.getId(),approvalType);
        List<ApprovalRecordCommunalView> approvalRecordCommunalViews = new ArrayList<>();
        if(list!=null){
            list.forEach(approvalRecord -> {
                ApprovalRecordCommunalView recordAdministratorView = ApprovalRecordCommunalView.builder()
                        .approvalType(approvalType).approvalNumber(approvalRecord.getApprovalNumber())
                        .approvalConsuming(approvalRecord.getApprovalConsuming())
                        .approvalTitle(approvalRecord.getApprovalTitle()).createTime(approvalRecord.getCreateTime())
                        .approvalRecordId(approvalRecord.getId()).approvalStatus(approvalRecord.getApprovalStatus())
                        .build();
                String approvalRecordId = approvalRecord.getId();
                //补卡
                if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                    CardReissueRecord cardReissueRecord = this.cardReissueRecordService.selectCardReissueRecordByApprovalRecordId(approvalRecordId);
                    recordAdministratorView.setSupplementaryCardCause(cardReissueRecord.getSupplementaryCardCause());
                    recordAdministratorView.setClockTimeDisplay(cardReissueRecord.getClockTimeDisplay());
                }
                //请假
                if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                    AskForLeaveRecord askForLeaveRecord = this.askForLeaveRecordService.selectAskForLeaveRecordByApprovalRecordId(approvalRecordId);
                    recordAdministratorView.setLeaveStartTimeAndroid(askForLeaveRecord.getLeaveStartTimeAndroid());
                    recordAdministratorView.setLeaveEndTimeAndroid(askForLeaveRecord.getLeaveEndTimeAndroid());
                }
                //外出
                if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                    GoOutRecord goOutRecord = this.goOutRecordService.selectGoOutRecordByApprovalRecordId(approvalRecordId);
                    recordAdministratorView.setDepartureTime(goOutRecord.getDepartureTime());
//                    System.err.println("departureTime="+goOutRecord.getDepartureTime());
                    recordAdministratorView.setEndOfOuting(goOutRecord.getEndOfOuting());
//                    System.err.println("endOfOuting="+goOutRecord.getEndOfOuting());
                    recordAdministratorView.setGoOutTime(goOutRecord.getGoOutTime());
                }
                approvalRecordCommunalViews.add(recordAdministratorView);
            });
        }
        PageInfo<ApprovalRecordCommunalView> p = new PageInfo<>(approvalRecordCommunalViews);
        return p;
    }

    /**
     * @方法名：selectApprovalDetailsViewByApprovalId
     * @描述： 根据审批记录id查询审批记录的详情
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 18:29
     */
    public ApprovalDetailsView selectApprovalDetailsViewByApprovalId(String approvalRecordId) {
        System.err.println("00-approvalRecordId="+approvalRecordId);
        ApprovalRecord approvalRecord = this.mapper.selectApprovalDetailsByApprovalId(approvalRecordId);
        Optional.ofNullable(approvalRecord).orElseThrow(() -> new BusinessException("no.data.approval.record"));
        String approvalType = approvalRecord.getApprovalType();
        //审批发起人
        UserView initiator = this.usersService.selectUserViewById(approvalRecord.getInitiatorId());
        //审批处理人
        UserView approver = this.usersService.selectUserViewById(approvalRecord.getApproverId());

        ApprovalDetailsView approvalDetailsView = new ApprovalDetailsView()
                //审批编号
                .setApprovalNumber(approvalRecord.getApprovalNumber())
                //审批标题
                .setApprovalTitle(approvalRecord.getApprovalTitle())
                //审批类型
                .setApprovalType(approvalType)
                //审批的发起时间
                .setInitiationTime(approvalRecord.getInitiationTime())
                //审批的完成时间
                .setFinishTime(approvalRecord.getFinishTime())
                //审批的结果(状态)
                .setApprovalStatus(approvalRecord.getApprovalStatus())
                //审批耗时
                .setApprovalConsuming(approvalRecord.getApprovalConsuming())
                //审批发起人
                .setInitiator(initiator)
                //审批处理人
                .setApprover(approver)
                //审批发起人id
                .setInitiatorId(approvalRecord.getInitiatorId())
                //审批处理人id
                .setApproverId(approvalRecord.getApproverId())
                //审批记录id
                .setApprovalRecordId(approvalRecordId);
        System.err.println("11-ApprovalRecordId="+approvalDetailsView.getApprovalRecordId());
        /** 补卡 */
        if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
            CardReissueRecord cardReissueRecord = this.cardReissueRecordService.selectCardReissueRecordByApprovalRecordId(approvalRecordId);
            approvalDetailsView
                    //事由(补卡原因)
                    .setReasons(cardReissueRecord.getSupplementaryCardCause())
                    //补卡班次显示
                    .setLackOfCardDivisions(cardReissueRecord.getLackOfCardDivisions())
                    //缺卡时间显示
                    .setClockTimeDisplay(cardReissueRecord.getClockTimeDisplay())
                    //考勤记录id
                    .setAttendanceRecordId(cardReissueRecord.getLackOfCardId())
                    //缺卡班次
                    .setShift(cardReissueRecord.getShift())
                    //图片url
                    .setImgUrl(cardReissueRecord.getImgUrl());
            System.err.println("LackOfCardDivisions="+cardReissueRecord.getLackOfCardDivisions());
        }
        System.err.println("22-ApprovalRecordId="+approvalDetailsView.getApprovalRecordId());
        /** 请假 */
        if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
            AskForLeaveRecord askForLeaveRecord = this.askForLeaveRecordService.selectAskForLeaveRecordByApprovalRecordId(approvalRecordId);
            approvalDetailsView
                    //请假事由
                    .setReasons(askForLeaveRecord.getReasonForALeave())
                    //请假时长
                    .setDuration(askForLeaveRecord.getLeaveTime())
                    //请假开始时间
                    .setLeaveStartTimeAndroid(askForLeaveRecord.getLeaveStartTimeAndroid())
                    //请假结束时间
                    .setLeaveEndTimeAndroid(askForLeaveRecord.getLeaveEndTimeAndroid())
                    //图片url
                    .setImgUrl(askForLeaveRecord.getImgUrl())
                    //附件url
                    .setAccessoryUrl(askForLeaveRecord.getAccessoryUrl());
        }
        System.err.println("33-ApprovalRecordId="+approvalDetailsView.getApprovalRecordId());
        /** 外出 */
        if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
            GoOutRecord goOutRecord = this.goOutRecordService.selectGoOutRecordByApprovalRecordId(approvalRecordId);
            approvalDetailsView
                    //外出事由
                    .setReasons(goOutRecord.getGoOutFor())
                    //外出开始时间
                    .setDepartureTime(goOutRecord.getDepartureTime())
                    //外出结束时间
                    .setEndOfOuting(goOutRecord.getEndOfOuting())
                    //外出时长
                    .setDuration(goOutRecord.getGoOutTime())
                    //交通费金额
                    .setCarFare(goOutRecord.getCarFare())
                    //图片url
                    .setImgUrl(goOutRecord.getImgUrl());

        }
        System.err.println("44-ApprovalRecordId="+approvalDetailsView.getApprovalRecordId());
        return approvalDetailsView;
    }

    /**
     * @方法名：revocationApprovalRecord
     * @描述： 根据审批记录id撤销自己发出的未被处理的请求
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 20:36
     */
    @Transactional(rollbackFor = Exception.class)
    public int revocationApprovalRecord(String approvalRecordId) {
        //获取到用户的登录信息,判断用户是否登录
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        String approvalStatus = this.mapper.selectApprovalStatusByApproverId(approvalRecordId);
        if(!VariableConstants.STRING_CONSTANT_1.equals(approvalStatus)){
            throw new BusinessException("irrevocable.approval");
        }
        int result = this.mapper.updateApprovalStatusSetFour(approvalRecordId);
        return result;
    }

    /**
     * @方法名：disposeCardReissueApproval
     * @描述： 管理端处理补卡审批
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/24 0:56
     */
    @Transactional(rollbackFor = Exception.class)
    public int disposeCardReissueApproval(CardReissueApprovalVo cardReissueApprovalVo) {
        int result = 0;
        String isConsent = cardReissueApprovalVo.getIsConsent();
        String approvalRecordId = cardReissueApprovalVo.getApprovalRecordId();
        System.err.println("approvalRecordId="+approvalRecordId);
        //完成时间
        LocalDateTime finishTime = LocalDateTime.now();
        //发起时间
        LocalDateTime initiationTime = DateUtil.strTransitionLocalDateTime(cardReissueApprovalVo.getInitiationTime());
        //审批耗时
        String approvalConsuming = DateUtil.computedTimeCheckFormat(initiationTime,finishTime);
        //拒绝通过
        if(VariableConstants.STRING_CONSTANT_0.equals(isConsent)){
            String refusalCause = cardReissueApprovalVo.getRefusalCause();
            result = this.mapper.updateApprovalStatusSetThree(refusalCause,approvalRecordId,finishTime,approvalConsuming);
        }else{
            //通过审批
            result = this.mapper.updateApprovalStatusSetTwo(approvalRecordId,finishTime,approvalConsuming);

            //班次(补上班的卡，还是下班的卡)
            String shift = cardReissueApprovalVo.getShift();
            System.err.println("shift="+shift);
            //缺卡那天记录的id
            String attendanceRecordId = cardReissueApprovalVo.getAttendanceRecordId();
            if(result>0){
                //执行补卡,更新补卡后的考勤记录
                int num = this.attendanceRecordService.disposeCardReissueApproval(shift,attendanceRecordId);
                System.err.println("补卡执行数据量="+num);
            }
        }

        /** 融云消息通知*/
        HashMap<String, String> map = new HashMap<>();
        //消息发起人
        String approverId = cardReissueApprovalVo.getApproverId();
        map.put("fromUserId",approverId);
        //消息接收人
        String initiatorId = cardReissueApprovalVo.getInitiatorId();
        map.put("toUserId",initiatorId);
        map.put("objectName","RC:TxtMsg");
        //审批的结果字样
        String consequence = Integer.parseInt(isConsent)==0?"拒绝":"同意";
        //审批的结果标识
        boolean agreeFlag =  Integer.parseInt(isConsent)==1?true:false;
        //标题
        String approvalTitle = "您的补卡申请已"+consequence+",请知晓";
        //补卡班次显示
        String lackOfCardDivisions = cardReissueApprovalVo.getLackOfCardDivisions();
        //补卡理由
        String supplementaryCardCause = cardReissueApprovalVo.getReasons();

        JSONObject approvalJsonObject = new JSONObject();
        approvalJsonObject.put("approvalType",VariableConstants.STRING_CONSTANT_1);
        approvalJsonObject.put("agreeFlag",agreeFlag);
        approvalJsonObject.put("approvalTitle",approvalTitle);
        approvalJsonObject.put("lackOfCardDivisions",lackOfCardDivisions);
        approvalJsonObject.put("supplementaryCardCause",supplementaryCardCause);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "审批");
        jsonObject.put("extra", approvalJsonObject.toJSONString());

        map.put("content",jsonObject.toJSONString());
        map.put("pushContent","审批");

        try {
            String s = RongUtils.groupManagement(map, "7");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @方法名：disposeAskForLeaveApproval
     * @描述： 管理端处理请假审批
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/24 14:36
     */
    @Transactional(rollbackFor = Exception.class)
    public int disposeAskForLeaveApproval(AskForLeaveApprovalVo askForLeaveApprovalVo) {
        int result = 0;
        String isConsent = askForLeaveApprovalVo.getIsConsent();
        String approvalRecordId = askForLeaveApprovalVo.getApprovalRecordId();
        System.err.println("请假审批approvalRecordId="+approvalRecordId);
        //完成时间
        LocalDateTime finishTime = LocalDateTime.now();
        //发起时间
        LocalDateTime initiationTime = DateUtil.strTransitionLocalDateTime(askForLeaveApprovalVo.getInitiationTime());
        //审批耗时
        String approvalConsuming = DateUtil.computedTimeCheckFormat(initiationTime,finishTime);

        //拒绝通过
        if(VariableConstants.STRING_CONSTANT_0.equals(isConsent)){
            String refusalCause = askForLeaveApprovalVo.getRefusalCause();
            result = this.mapper.updateApprovalStatusSetThree(refusalCause,approvalRecordId,finishTime,approvalConsuming);
            System.err.println("拒绝请假="+result);
        }else{
            //通过审批
            result = this.mapper.updateApprovalStatusSetTwo(approvalRecordId,finishTime,approvalConsuming);
            if(result>0){
                /** 通过请假后，要更新请假人的考勤记录 */
                //开始请假那天的日期
                String leaveStartTimeAndroid = askForLeaveApprovalVo.getLeaveStartTimeAndroid();
                System.err.println("leaveStartTimeAndroid="+leaveStartTimeAndroid);
                String[] startLeaveTimeArray = leaveStartTimeAndroid.split(" ");
                //为了避免传入 2019-12-3 会报错的问题，先处理一道转换成 2019-12-03
                String startLeaveDateStr = AttendanceUtil.parseDateStr(startLeaveTimeArray[0]);
                LocalDate startLeaveDate = LocalDate.parse(startLeaveDateStr);
                String startLeaveTime = startLeaveTimeArray[1];
                //结束请假那天的日期
                String leaveEndTimeAndroid = askForLeaveApprovalVo.getLeaveEndTimeAndroid();
                System.err.println("leaveEndTimeAndroid="+leaveEndTimeAndroid);
                String[] leaveEndTimeArray = leaveEndTimeAndroid.split(" ");
                //为了避免传入 2019-12-3 会报错的问题，先处理一道转换成 2019-12-03
                String leaveEndDateStr = AttendanceUtil.parseDateStr(leaveEndTimeArray[0]);
                LocalDate leaveEndDate =  LocalDate.parse(leaveEndDateStr);
                System.err.println("leaveEndDate="+leaveEndDate);
                String leaveEndTime = leaveEndTimeArray[1];
                //把执行请假 需要的数据进行包装
                AgreedToAskForLeaveVo agreedToAskForLeaveVo = new AgreedToAskForLeaveVo()
                        .setInitiatorId(askForLeaveApprovalVo.getInitiatorId())
                        .setStartLeaveDate(startLeaveDate)
                        .setStartLeaveTime(startLeaveTime)
                        .setLeaveEndDate(leaveEndDate)
                        .setLeaveEndTime(leaveEndTime)
                        .setDuration(Double.valueOf(askForLeaveApprovalVo.getDuration()));
                //更新考勤状态
                int num = this.attendanceRecordService.disposeAskForLeaveApproval(agreedToAskForLeaveVo);
                System.err.println("请假执行数据量="+num);
            }
        }

        /** 融云消息通知*/
        HashMap<String, String> map = new HashMap<>();
        //消息发起人
        String approverId = askForLeaveApprovalVo.getApproverId();
        map.put("fromUserId",approverId);
        //消息接收人
        String initiatorId = askForLeaveApprovalVo.getInitiatorId();
        map.put("toUserId",initiatorId);
        //审批的结果字样
        String consequence = Integer.parseInt(isConsent)==0?"拒绝":"同意";
        //审批的结果标识
        boolean agreeFlag =  Integer.parseInt(isConsent)==1?true:false;
        //标题
        String approvalTitle = "您的请假申请已"+consequence+",请知晓";
        //请假开始时间
        String leaveStartTime = askForLeaveApprovalVo.getLeaveStartTimeAndroid();
        //请假结束时间
        String leaveEndTime = askForLeaveApprovalVo.getLeaveEndTimeAndroid();

        JSONObject approvalJsonObject = new JSONObject();
        approvalJsonObject.put("approvalType",VariableConstants.STRING_CONSTANT_2);
        approvalJsonObject.put("agreeFlag",agreeFlag);
        approvalJsonObject.put("approvalTitle",approvalTitle);
        approvalJsonObject.put("leaveStartTime",leaveStartTime);
        approvalJsonObject.put("leaveEndTime",leaveEndTime);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "审批");
        jsonObject.put("extra", approvalJsonObject.toJSONString());
        map.put("objectName","RC:TxtMsg");
        map.put("content",jsonObject.toJSONString());
        map.put("pushContent","审批");

        try {
            String s = RongUtils.groupManagement(map, "7");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @方法名：disposeGoOutApproval
     * @描述： 管理端处理外出审批
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/24 19:38
     */
    @Transactional(rollbackFor = Exception.class)
    public int disposeGoOutApproval(GoOutApprovalVo goOutApprovalVo) {
        int result = 0;
        String isConsent = goOutApprovalVo.getIsConsent();
        String approvalRecordId = goOutApprovalVo.getApprovalRecordId();
        System.err.println("approvalRecordId="+approvalRecordId);
        //完成时间
        LocalDateTime finishTime = LocalDateTime.now();
        //发起时间
        LocalDateTime initiationTime = DateUtil.strTransitionLocalDateTime(goOutApprovalVo.getInitiationTime());
        //审批耗时
        String approvalConsuming = DateUtil.computedTimeCheckFormat(initiationTime,finishTime);

        //拒绝通过
        if(VariableConstants.STRING_CONSTANT_0.equals(isConsent)){
            String refusalCause = goOutApprovalVo.getRefusalCause();
            result = this.mapper.updateApprovalStatusSetThree(refusalCause,approvalRecordId,finishTime,approvalConsuming);
        }else{
            //通过审批
            result = this.mapper.updateApprovalStatusSetTwo(approvalRecordId,finishTime,approvalConsuming);
            if(result>0){
                //通过外出申请后，要更新外出人员的考勤记录
                AgreedGoOutVo agreedGoOutVo = new AgreedGoOutVo()
                        .setDepartureTime(goOutApprovalVo.getDepartureTime())
                        .setEndOfOuting(goOutApprovalVo.getEndOfOuting())
                        .setDuration(goOutApprovalVo.getDuration())
                        .setInitiatorId(goOutApprovalVo.getInitiatorId());
                //更新考勤记录的状态
                int num = this.attendanceRecordService.disposeGoOutApproval(agreedGoOutVo);
                System.err.println("外出执行数据量="+num);
            }
        }

        /** 融云消息通知*/
        HashMap<String, String> map = new HashMap<>();
        //消息发起人
        String approverId = goOutApprovalVo.getApproverId();
        map.put("fromUserId",approverId);
        //消息接收人
        String initiatorId = goOutApprovalVo.getInitiatorId();
        map.put("toUserId",initiatorId);

        //审批的结果字样
        String consequence = Integer.parseInt(isConsent)==0?"拒绝":"同意";
        //审批的结果标识
        boolean agreeFlag =  Integer.parseInt(isConsent)==1?true:false;
        //标题
        String approvalTitle = "您的外出申请已"+consequence+",请知晓";
        //外出开始时间
        String departureTime = DateUtil.getFormatterYMDHM(goOutApprovalVo.getDepartureTime());
        //外出结束时间
        String endOfOuting = DateUtil.getFormatterYMDHM(goOutApprovalVo.getEndOfOuting());
        //外出时长
        String duration = goOutApprovalVo.getDuration();

        JSONObject approvalJsonObject = new JSONObject();
        approvalJsonObject.put("approvalType",VariableConstants.STRING_CONSTANT_3);
        approvalJsonObject.put("agreeFlag",agreeFlag);
        approvalJsonObject.put("approvalTitle",approvalTitle);
        approvalJsonObject.put("departureTime",departureTime);
        approvalJsonObject.put("endOfOuting",endOfOuting);
        approvalJsonObject.put("duration",duration);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("content", "审批");
        jsonObject.put("extra", approvalJsonObject.toJSONString());

        map.put("content",jsonObject.toJSONString());
        map.put("pushContent","审批");
        map.put("objectName","RC:TxtMsg");

        try {
            String s = RongUtils.groupManagement(map, "7");
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @方法名：selectApprovalRecordBackViewByCondition
     * @描述： 后台-按条件审批记录列表(带分页)
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/26 9:50
     */
    public PageInfo<ApprovalRecordBackView> selectApprovalRecordBackViewByCondition(ApprovalRecordBackVo approvalRecordBackVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();
        System.err.println(scenicId);
        approvalRecordBackVo.setScenicId(scenicId);

        Page page = PageHelper.startPage(approvalRecordBackVo.getNum(),approvalRecordBackVo.getSize());
        List<ApprovalRecord> list = this.mapper.selectApprovalRecordByCondition(approvalRecordBackVo);
        List<ApprovalRecordBackView> backViewList = new ArrayList<>();
        list.forEach(approvalRecord -> {
            ApprovalRecordBackView approvalRecordBackView = new ApprovalRecordBackView().setApprovalConsuming(approvalRecord.getApprovalConsuming())
                    .setId(approvalRecord.getId()).setApprovalNumber(approvalRecord.getApprovalNumber())
                    .setApprovalTitle(approvalRecord.getApprovalTitle()).setInitiationTime(approvalRecord.getInitiationTime())
                    .setFinishTime(approvalRecord.getFinishTime()).setCreateTime(approvalRecord.getCreateTime());
            //审批类型Display
            String approvalTypeDiplay = DictUtil.getDisplay("approvalType",approvalRecord.getApprovalType());
            //审批的结果 Display
            String approvalStatusDisplay = DictUtil.getDisplay("approvalStatus",approvalRecord.getApprovalStatus());
            //请求人姓名
            String initiatorName = this.usersService.selectNiceNameById(approvalRecord.getInitiatorId());
            //审批人姓名
            String approverNmae = this.usersService.selectNiceNameById(approvalRecord.getApproverId());
            approvalRecordBackView.setApprovalTypeDiplay(approvalTypeDiplay)
                    .setApprovalStatusDisplay(approvalStatusDisplay)
                    .setInitiatorName(initiatorName)
                    .setApproverNmae(approverNmae);
            backViewList.add(approvalRecordBackView);
        });
        PageInfo<ApprovalRecordBackView> pageInfo = new PageInfo<>(backViewList);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }
}
